package net.caixiaomi.info.Lottery.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;

import net.caixiaomi.info.Lottery.adapter.LotteryOrderAdapter;
import net.caixiaomi.info.Lottery.model.BallItem;
import net.caixiaomi.info.Lottery.model.LotteryBettingEntity;
import net.caixiaomi.info.Lottery.model.LotteryOrderCathecticEntity;
import net.caixiaomi.info.Lottery.model.LotteryOrderDetail;
import net.caixiaomi.info.Lottery.view.BallOrderEntity;
import net.caixiaomi.info.Lottery.view.BallOrderView;
import net.caixiaomi.info.R;
import net.caixiaomi.info.WebViewActivity;
import net.caixiaomi.info.adapter.OrderInfoAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.entity.MultiItemEntity;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.OrderInfoItem;
import net.caixiaomi.info.model.OrderInfoModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.order.PriceTicketPlanActivity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;

import static android.R.id.list;

/**
 * Created by suntian on 2018/8/19.
 */

public class LotteryOrderDetailActivity extends BaseActivity implements View.OnClickListener, OnRefreshListener {

    private String mOrderId;

    @BindView(list)
    RecyclerView mListView;
    @BindView(R.id.progress)
    CircularProgressBar mProgress;

    @BindView(R.id.refresh)
    SmartRefreshLayout mRefreshLayout;

    private ImageView mIcon;
    private TextView mName;
    private TextView mPrice;//花费钱
    private ImageView mStatusImg;
    private TextView mPlanStatus;//订单状态
    private TextView mWinnerTimerDes;
    private BallOrderView mWinnerBallView;

    private TextView mWinnerMoney;
    private TextView mWinnerDes;
    private LinearLayout mWinnerGroup;


    private TextView mOrderNum;//方案编号
    private TextView mCreateTime;//创建时间
    private TextView mPickTime;//店主接单
    private TextView mPrintTicketTime;//店主出票

    private LotteryOrderAdapter mAdapter;
    private LotteryOrderDetail mOrderInfo;

    private HashMap<String,String> orderStatusContainer;

    private List<LotteryOrderCathecticEntity> mList;

    @Override
    protected int layout() {
        return R.layout.lottery_order_detail_layout;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mOrderId = getIntent().getStringExtra("id");
        initView();
        loadData();
    }
    private void initView() {
        try {
            mList=new ArrayList<>();
            mRefreshLayout.setOnRefreshListener(this);

            findViewById(R.id.lottery_order_left_btn).setOnClickListener(this);
            findViewById(R.id.lottery_order_right_btn).setOnClickListener(this);

            View headerView = LayoutInflater.from(this).inflate(R.layout.lottery_order_top_layout, null);
            mIcon = (ImageView) headerView.findViewById(R.id.lottery_logo_img);
            mName = (TextView) headerView.findViewById(R.id.lottery_logo_tv);
            mPrice = (TextView) headerView.findViewById(R.id.lottery_logo_price);
            mStatusImg=headerView.findViewById(R.id.lottery_logo_status_img);

            mWinnerGroup=headerView.findViewById(R.id.lottery_order_win_group);
            mWinnerMoney=headerView.findViewById(R.id.lottery_order_win_money);
            mWinnerDes=headerView.findViewById(R.id.lottery_order_win_money_des);

            mPlanStatus = (TextView) headerView.findViewById(R.id.plan_status);
            mWinnerTimerDes=headerView.findViewById(R.id.lottery_winner_timer_des);
            mWinnerBallView=headerView.findViewById(R.id.lottery_order_winner_ball);
//            mLotteryPriceInfo = (TextView) headerView.findViewById(R.id.lottery_info);
//            mPlanResult = (TextView) headerView.findViewById(R.id.plan_result);

            View footerView = LayoutInflater.from(this).inflate(R.layout.footer_order_lottery_info, null);

            footerView.findViewById(R.id.btn_look).setOnClickListener(this);
            footerView.findViewById(R.id.footer_des_what_prize).setOnClickListener(this);
            mOrderNum = (TextView) footerView.findViewById(R.id.order_num);
            mCreateTime = (TextView) footerView.findViewById(R.id.create_time);
            mPickTime = (TextView) footerView.findViewById(R.id.pick_time);
            mPrintTicketTime = (TextView) footerView.findViewById(R.id.print_ticket_time);

            mAdapter = new LotteryOrderAdapter(null);
            mAdapter.addHeaderView(headerView);
            mAdapter.addFooterView(footerView);
            mListView.setLayoutManager(new LinearLayoutManager(this));
            mListView.setAdapter(mAdapter);

            orderStatusContainer=new HashMap<>();
            orderStatusContainer.put("0","待付款");
            orderStatusContainer.put("1","待出票");
            orderStatusContainer.put("2","出票失败");
            orderStatusContainer.put("3","待开奖");
            orderStatusContainer.put("4","未中奖");
            orderStatusContainer.put("5","已中奖");
            orderStatusContainer.put("6","派奖中");
            orderStatusContainer.put("7","审核中");
            orderStatusContainer.put("8","支付失败");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("orderId", mOrderId);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<LotteryOrderDetail>> orderDetail = requestService.getLottoOrderDetail(params);
        orderDetail.enqueue(new ResponseCallback<BaseCallModel<LotteryOrderDetail>>() {
            @Override
            public void onSuccess(BaseCallModel<LotteryOrderDetail> data) {
                mRefreshLayout.finishRefresh();
                mProgress.setVisibility(View.GONE);
                mOrderInfo = data.data;
                bindData(mOrderInfo);
            }

            @Override
            public void onFail(ResponseError error) {
                mRefreshLayout.finishRefresh();
                mProgress.setVisibility(View.GONE);
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {
                mRefreshLayout.finishRefresh();
                mProgress.setVisibility(View.GONE);
            }
        });
    }

    private void bindData(LotteryOrderDetail model) {
        try {
            mList.clear();
            Glide.with(this).load(model.getLotteryClassifyImg()).into(mIcon);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(getString(R.string.C_MONEY_CHAT)).append(model.getTicketAmount());
            String price = stringBuilder.toString();
            stringBuilder.setLength(0);

            mName.setText(model.getLotteryClassifyName()+"   "+model.getTermNum()+"期");
            mPrice.setText(price);
            mPlanStatus.setText(orderStatusContainer.get(model.getOrderStatus()));

            String status=model.getOrderStatus();
            if(TextUtils.equals(status,"2")||TextUtils.equals(status,"4")||TextUtils.equals(status,"5")||TextUtils.equals(status,"6")||TextUtils.equals(status,"7")){
                mWinnerGroup.setVisibility(View.VISIBLE);
                if(TextUtils.equals(status,"2")) {
                    mWinnerDes.setText("");
                    mWinnerMoney.setText("资金已退回");
                    mWinnerMoney.setTextColor(getResources().getColor(R.color.primary_text));
                }else if(TextUtils.equals(status,"4")){
                    mWinnerMoney.setText("感谢您助力公益事业");
                    mWinnerMoney.setTextSize(14);
                    mWinnerMoney.setTextColor(getResources().getColor(R.color.primary_text));
                    mWinnerDes.setText("");
                }else{
                    mWinnerMoney.setText(getString(R.string.C_MONEY_CHAT) + model.getWinningMoney());
                }
            }else{
                mWinnerGroup.setVisibility(View.GONE);
            }
            if(TextUtils.equals(status,"4")||TextUtils.equals(status,"5")||TextUtils.equals(status,"6")||TextUtils.equals(status,"7")){
                mWinnerTimerDes.setVisibility(View.GONE);
                mWinnerBallView.setVisibility(View.VISIBLE);
                List<BallOrderEntity> list=new ArrayList<>();
                for(int i=0;i<model.getPrizeNum().size();i++){
                    String num=model.getPrizeNum().get(i);
                    BallOrderEntity ballItem=new BallOrderEntity();
                    ballItem.setNum(num);
                    if(i<5) {
                        ballItem.setColorType(0);
                    }else{
                        ballItem.setColorType(2);
                    }
                    if(i==4){
                        ballItem.setDivider(1);
                    }
                    list.add(ballItem);
                }
                mWinnerBallView.setEntity(list,7);
                mStatusImg.setVisibility(View.VISIBLE);
                if(TextUtils.equals(status,"4")){
                    mStatusImg.setBackgroundResource(R.drawable.lottery_no_prize);
                }else{
                    mStatusImg.setBackgroundResource(R.drawable.lottery_has_prize);
                }
            }else{
                mWinnerTimerDes.setVisibility(View.VISIBLE);
                mWinnerTimerDes.setText(model.getPrePrizeInfo());
                mWinnerBallView.setVisibility(View.GONE);
                mStatusImg.setVisibility(View.GONE);
            }

            SpannableString spannableString = new SpannableString(stringBuilder);
            stringBuilder.setLength(0);
            stringBuilder.append(getString(R.string.C_PLAN_NUM)).append(": ").append(model.getProgrammeSn());
            spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text)), stringBuilder.length() - model.getProgrammeSn().length(), stringBuilder.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mOrderNum.setText(spannableString);

            stringBuilder.setLength(0);
            stringBuilder.append(getString(R.string.C_ORDER_CREATE_TIME)).append(": ").append(model.getCreateTime());
            spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text)), stringBuilder.length() - model.getCreateTime().length(), stringBuilder.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mCreateTime.setText(spannableString);

            stringBuilder.setLength(0);
            stringBuilder.append(getString(R.string.C_ORDER_PICK_UP_TIME)).append(": ").append(model.getAcceptTime());
            spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text)), stringBuilder.length() - model.getAcceptTime().length(), stringBuilder.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mPickTime.setText(spannableString);

            stringBuilder.setLength(0);
            stringBuilder.append(getString(R.string.C_ORDER_OUT_TIME)).append(": ").append(model.getTicketTime());
            spannableString = new SpannableString(stringBuilder);
            spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.primary_text)), stringBuilder.length() - model.getTicketTime().length(), stringBuilder.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            mPrintTicketTime.setText(spannableString);

//            mAdapter.getData().clear();
            List<MultiItemEntity>list=new ArrayList<>();
            List<LotteryOrderCathecticEntity> ll= model.getCathecticResults();
            mList.addAll(ll);
            list.addAll(ll);
            mAdapter.setNewData(list);
//            mAdapter.addData(model.getCathecticResults());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_look:
                if (mOrderInfo != null) {
                    Intent intent = new Intent(this, LotteryPriceTicketPlanActivity.class);
                    intent.putExtra("sn", mOrderInfo.getOrderSn());
                    intent.putExtra("psn", mOrderInfo.getProgrammeSn());
                    startActivity(intent);
                }
                break;
            case R.id.lottery_order_left_btn:
                CommonApp.mLotteryIndex=-1;
                CommonApp.mLotteryBettingList.clear();
                for(int i=0;i<mList.size();i++){
                    LotteryBettingEntity entity=getData(mList.get(i));
                    CommonApp.mLotteryBettingList.add(entity);
                }
                CommonApp.mLotteryIndex=-2;
                Intent intented=new Intent(this,LotteryBettingConfirmActivity.class);
                startActivity(intented);
                break;
            case R.id.lottery_order_right_btn:
                Intent intent=new Intent(this, BallLotteryMainActivity.class);
                startActivity(intent);
                break;
            case R.id.footer_des_what_prize:
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(Constants.BASE_H5_URL).append("daletou/playHelp");
                String url = stringBuilder.toString();
                Intent intentedd = new Intent(this, WebViewActivity.class);
                intentedd.putExtra("url", url);
                startActivity(intentedd);
                break;
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        loadData();
    }

    private LotteryBettingEntity getData(LotteryOrderCathecticEntity target){
        LotteryBettingEntity entity=new LotteryBettingEntity();

        CommonApp.mAddChip=target.getIsAppend()==1;
        CommonApp.mTrebleNum=target.getCathectic();
        long lMoney=Long.parseLong(target.getAmount());
        if(target.getIsAppend()==1){
            lMoney=2*lMoney/3;
        }
        lMoney=lMoney/CommonApp.mTrebleNum;

        if(target.getPlayType()!=2){
            List<String> befores=new ArrayList<>();
            List<String> afters=new ArrayList<>();
            for(int i=0;i<target.getRedCathectics().size();i++){
                String num=target.getRedCathectics().get(i).getCathectic();
                befores.add(num);
            }
            for(int i=0;i<target.getBlueCathectics().size();i++){
                String num=target.getBlueCathectics().get(i).getCathectic();
                afters.add(num);
            }
            entity.setmBefores(befores);
            entity.setmAfters(afters);
            if(befores.size()==5&&afters.size()==2){
                entity.setStatus(0);
            }else{
                entity.setStatus(1);
            }
            entity.setChips(target.getBetNum());

            entity.setMoney(lMoney);
        }else{
            List<String> beforeDans=new ArrayList<>();
            List<String> afterDans=new ArrayList<>();
            List<String> beforeTuos=new ArrayList<>();
            List<String> afterTuos=new ArrayList<>();
            for(int i=0;i<target.getRedDanCathectics().size();i++){
                String num=target.getRedDanCathectics().get(i).getCathectic();
                beforeDans.add(num);
            }
            for(int i=0;i<target.getRedTuoCathectics().size();i++){
                String num=target.getRedTuoCathectics().get(i).getCathectic();
                beforeTuos.add(num);
            }
            for(int i=0;i<target.getBlueDanCathectics().size();i++){
                String num=target.getBlueDanCathectics().get(i).getCathectic();
                afterDans.add(num);
            }
            for(int i=0;i<target.getBlueTuoCathectics().size();i++){
                String num=target.getBlueTuoCathectics().get(i).getCathectic();
                afterTuos.add(num);
            }
            entity.setStatus(2);
            entity.setmBeforeDans(beforeDans);
            entity.setmBeforeTuos(beforeTuos);
            entity.setmAfterDans(afterDans);
            entity.setmAfterTuos(afterTuos);
            entity.setChips(target.getBetNum());
            entity.setMoney(lMoney);
        }
        return entity;
    }
}
